import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import { debounce } from "lodash";

const IS_PROD = process.env.NODE_ENV === "production";
const baseURL: string = IS_PROD ? window.service.api_url : "/api";
const message: any = ElMessage;

function errorMessage(msg: string) {
  return message({
    type: "error",
    message: msg,
    dangerouslyUseHTMLString: true,
    duration: 2500
  });
}
export const instance = axios.create({
  baseURL,
  timeout: 20000,
  validateStatus: (statusCode: number): boolean => {
    return statusCode >= 200 && statusCode < 300;
  }
});
instance.interceptors.request.use(
  (request: any) => {
    if (request.headers["Content-Type"] !== "multipart/form-data") {
      // 过滤文件数据
      if (
        (request.method === "post" || request.method === "put") &&
        request.headers["Content-Type"] !== "application/x-www-form-urlencoded"
      ) {
        request.headers["Content-Type"] = "application/json";
        // config.data = window.crypto.en(JSON.parse(JSON.stringify(config.data)));
      }
    } else {
      // 处理文件请求时间
      request.timeout = 2160000;
    }

    // 携带token的拦截
    // const token = getTokenCache();
    // if (token) {
    //   request.headers.Authorization = `bearer ${token}`;
    // }

    return request;
  },
  e => {
    return Promise.reject(e);
  }
);
const whenServiceStop = () => {
  errorMessage("服务未启动");
};
const onServiceStop = debounce(whenServiceStop, 500);
instance.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    const { data } = response;
    // if (data.code > 500 && data.code < 600) {
    //   errorMessage("后台服务器正在部署中，请你稍等！");
    //   return Promise.reject();
    // }
    // if (data.meta && !data.meta.success) {
    //   errorMessage(data.meta.message);
    // return Promise.reject();
    // }
    return data;
  },
  error => {
    const { response } = error;
    if (response && response.status === 401) {
      // login();
      return;
    }
    if (response && (response.status === 503 || response.status === 504)) {
      onServiceStop();
      return;
    }
    errorMessage(error);
    return Promise.reject(error);
  }
);
